<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      ref="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-input
          v-model="dataForm.key"
          placeholder="参数名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="" prop="startTime">
        <el-date-picker
          v-model="dataForm.startTime"
          type="date"
          placeholder="选择开始日期"
          :picker-options="startTime"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd 00:00:00"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" prop="endTime">
        <el-date-picker
          v-model="dataForm.endTime"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd 23:59:59"
          placeholder="选择结束日期"
          :picker-options="endTime"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()" type="primary">查询</el-button>
        <el-button @click="resetForm('dataForm')">重置</el-button>
        <el-button
          v-if="isAuth('sys:dept:save')"
          type="primary"
          @click="addOrUpdateHandle()"
          >新增</el-button
        >
        <el-button
          v-if="isAuth('sys:dept:batchDelete')"
          type="danger"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      ref="tableRef"
      v-loading="dataListLoading"
      border
      default-expand-all
      select-on-indeterminate
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :data="dataList"
      row-key="deptId"
      @selection-change="selectionChangeHandle"
      @select="rowSelect"
      @select-all="selectAll"
      style="width: 100%"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="55" />
      <el-table-column
        prop="deptId"
        header-align="center"
        align="center"
        width="80"
        label="ID"
      >
      </el-table-column>
      <el-table-column label="名称" prop="name" />
      <el-table-column label="排序" prop="deptSort" />
      <el-table-column label="状态" align="center" prop="enabled">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            :disabled="scope.row.deptId === 1"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeEnabled(scope.row, scope.row.enabled)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建日期" />
      <el-table-column label="操作" width="130px" align="center" fixed="right">
        <!-- <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :disabled-dle="scope.row.id === 1"
            msg="确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！"
          />
        </template> -->
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            v-if="isAuth('sys:dept:update')"
            @click="addOrUpdateHandle(scope.row.deptId)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            v-if="isAuth('sys:dept:delete')"
            @click="deleteHandle(scope.row.deptId)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination> -->
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from "./dept-add-or-update";
import Vue from "vue";
export default {
  data() {
    return {
      //日期的限制
      startTime: {
        // 禁用的日期
        disabledDate: time => {
          // 如果已经已知结束日期，就把结束日期之后的日期禁用
          if (this.dataForm.endTime) {
            return time.getTime() > new Date(this.dataForm.endTime).getTime();
          } else {
            // 否则 就把当前日期之后的日期禁用掉
            // return time.getTime() > Date.now()
          }
        }
      },
      endTime: {
        disabledDate: time => {
          // 如果已知开始日期，就把开始日期之前的日期禁用掉
          if (this.dataForm.startTime) {
            return time.getTime() < new Date(this.dataForm.startTime).getTime();
          }
        }
      },
      dataForm: {
        key: "",
        startTime: null,
        endTime: null
      },

      pid: "",
      updateStatus: "",
      dataList: [],
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      selectFlag: false
    };
  },
  components: {
    AddOrUpdate
  },
  activated() {
    this.getDataList();
  },
  // created(){
  //    this.getDataList();
  // },
  // mounted() {
  //   debugger

  // },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.getDataList();
    },
    // 改变状态
    changeEnabled(data, val) {
      if (val === "1") {
        this.updateStatus = "启用";
      } else {
        this.updateStatus = "停用";
      }
      this.$confirm(
        '此操作将 "' +
          this.updateStatus +
          '" ' +
          data.name +
          "部门, 是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sys/dept/updateEnabled"),
            method: "post",
            data: this.$http.adornData({
              enabled: val,
              deptId: data.deptId
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success"
              });
              this.getDataList();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {
          data.enabled = !data.enabled;
        });
    },
    toggleSelection(rows, flag) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.tableRef.toggleRowSelection(row, flag);
          if (row.children) {
            this.toggleSelection(row.children, flag);
          }
        });
      }
    },
    //全选的事件
    selectAll(selection) {
      if (!this.selectFlag) {
        this.toggleSelection(selection, true);
        this.addSelect(this.dataList, true);
      } else {
        this.$refs.tableRef.clearSelection();
        this.addSelect(this.dataList, false);
      }
      this.selectFlag = !this.selectFlag;
    },
    // 树形表多选，添加select字段区分当前行是否被选中
    // 为了：当所有子节点取消选中，父节点也要取消选中；当所有子节点已选中，父节点也要相应选中
    // element文档貌似没相关操作
    addSelect(data, flag) {
      data.forEach((item, index) => {
        Vue.set(item, "select", flag);
        if (data[index].children) {
          this.addSelect(data[index].children, flag);
        }
      });
    },
    //单行选择
    rowSelect(selection, row) {
      // 全选 or 取消全选
      if (selection.indexOf(row) > -1) {
        this.toggleSelection(row.children, true);
        row.select = true;
        if (row.children) {
          this.addSelect(row.children, true);
        }
      } else if (selection.indexOf(row) == -1) {
        this.toggleSelection(row.children, false);
        row.select = false;
        if (row.children) {
          this.addSelect(row.children, false);
        }
      }
      this.getParent(this.dataList, row);
    },
    // 获取父节点并操作
    // 当所有子节点取消选中，父节点也要取消选中；当所有子节点已选中，父节点也要相应选中
    getParent(data, row) {
      data.forEach(item => {
        //判断该行是否有子节点
        if (item.children) {
          //遍历子节点
          item.children.forEach(item2 => {
            //判断该节点是否为我点击的节点
            if (item2.deptId == row.deptId) {
              // 去遍历被点击节点的父节点
              if (item.children) {
                let rowParentFlag = true;
                item.children.forEach(i => {
                  rowParentFlag = i.select && rowParentFlag;
                });
                // 当所有节点都被选中，父节点打勾
                if (rowParentFlag) {
                  this.$refs.tableRef.toggleRowSelection(item, true);
                  item.select = true;
                  // 获取父节点的父节点进行判断
                  this.getParent(this.dataList, item);
                } else {
                  // 兄弟节点只要有一个节点没打勾，父节点都要取消打勾
                  this.$refs.tableRef.toggleRowSelection(item, false);
                  item.select = false;
                  // 获取父节点的父节点进行判断
                  this.getParent(this.dataList, item);
                }
              }
            } else if (item.children) {
              this.getParent(item.children, row);
            }
          });
        }
      });
    },
    selectChange() {},
    selectAllChange() {},
    selectionChangeHandler() {},
    checkboxT(row, rowIndex) {
      return row.deptId !== 1;
    },
    // getDeptDatas(tree, treeNode, resolve) {
    //   let keys = ''
    //    this.dataListLoading = true;
    //   this.$http({
    //     url: this.$http.adornUrl("/sys/dept/list"),
    //     method: "get",
    //     params: this.$http.adornParams({
    //       key: keys,
    //       pid:tree.deptId,
    //     })
    //   }).then(({ data }) => {
    //     if (data && data.code === 0) {
    //      resolve(data.list)
    //     } else {
    //       this.dataList = [];
    //     }
    //     this.dataListLoading = false;
    //   });
    // },
    // 获取数据列表
    getDataList() {
      debugger;
      this.dataListLoading = true;
      console.log("this.dataForm", this.dataForm);
      this.$http({
        url: this.$http.adornUrl("/sys/dept/list"),
        method: "get",
        params: this.$http.adornParams({
          key: this.dataForm.key,
          pid: this.pid,
          startTime: this.dataForm.startTime,
          endTime: this.dataForm.endTime
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.list;
          this.addSelect(this.dataList, false);
          console.log("this.dataList", this.dataList);
        } else {
          this.dataList = [];
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.deptId;
          });
      this.$confirm(
        `确定删除吗,如果存在下级节点则一并删除，此操作不能撤销?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/sys/dept/delete"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    }
  }
};
</script>
